﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;

namespace SuperiorCommon
{
    public class CacheHelper
    {
        public CacheHelper()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /*
    Add 	
    将数据添加到Cache对象
    Insert 	
    向Cache中插入数据项，可用于修改已经存在的数据缓存项
    Remove 	
    移除Cache对象中的缓存数据项
    Get 	
    从Cache对象中获取指定的数据项，注意返回的是Object类型，需要进行类型转换
    GetType 	
    从Cache对象中获取数据项的类型，判断数据类型后，方便进行转换
    GetEnumerator 	
    循环访问Cache对象中的缓存数据项。注意其返回类型是“IDictionaryEnumerator”
          */
        /// <summary>
        /// 获取当前应用程序指定CacheKey的Cache对象值 
        /// </summary>
        /// <param name="CacheKey">索引键值</param>
        /// <returns>返回缓存对象</returns> 
        public static T GetCache<T>(string CacheKey)
        {
            T t = default(T);
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            object o = objCache[CacheKey];
            if (o != null)
            {
                t = (T)o;
            }

            return t;
        }

        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <returns></returns>
        public static object GetCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            object o = objCache[CacheKey];
            return o;
        }

        /// <summary>
        /// 清除所有缓存
        /// </summary>
        public static void RemoveAllCache()
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
            ArrayList al = new ArrayList();
            while (CacheEnum.MoveNext())
            {
                al.Add(CacheEnum.Key);
            }
            foreach (string key in al)
            {
                _cache.Remove(key);
            }
        }

        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache对象值
        /// </summary>
        /// <param name="CacheKey">索引键值</param>
        /// <param name="objObject">缓存对象</param>
        public static void SetCache(string CacheKey, object objObject)
        {
            if (objObject == null)
            {
                if (!string.IsNullOrEmpty(CacheKey))
                {
                    RemoveCache(CacheKey);
                }

                return;
            }

            string timeSpanStr = System.Configuration.ConfigurationManager.AppSettings["CacheTime"];

            int timeSpan = 0;

            bool b = int.TryParse(timeSpanStr, out timeSpan);
            if (!b)
            {
                // 默认60分钟过期
                timeSpan = 60;
            }

            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, DateTime.Now.AddMinutes(timeSpan), TimeSpan.Zero);
        }

        /// <summary>
        /// 缓存时间
        /// </summary>f
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        /// <param name="time"></param>
        public static void SetCache(string CacheKey, object objObject, int cacheTime)
        {
            int timeSpan = cacheTime;
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, DateTime.Now.AddMinutes(timeSpan), TimeSpan.Zero);
        }

        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <param name="CacheKey"></param>
        public static void RemoveCache(string CacheKey)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Remove(CacheKey);
        }

        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache对象值
        /// </summary>
        /// <param name="CacheKey">索引键值</param>
        /// <param name="objObject">缓存对象</param>
        /// <param name="absoluteExpiration">绝对过期时间</param>
        /// <param name="slidingExpiration">最后一次访问所插入对象时与该对象过期时之间的时间间隔</param>
        public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
        }


        public static List<string> GetAllKeys()
        {
            List<string> keys = new List<string>();

            System.Web.Caching.Cache objCache = HttpRuntime.Cache;
            // retrieve application Cache enumerator
            IDictionaryEnumerator enumerator = objCache.GetEnumerator();
            // copy all keys that currently exist in Cache
            while (enumerator.MoveNext())
            {
                keys.Add(enumerator.Key.ToString());
            }

            return keys;
        }


        ///// <summary>
        ///// 文件缓存
        ///// </summary>
        ///// <param name="fileName"></param>
        ///// <returns></returns>
        //public static string GetFileCache(string fileName)
        //{
        //    string key = fileName;
        //    string text = GetCache<string>(key);

        //    if (string.IsNullOrEmpty(text))
        //    {
        //        string timeSpanStr = System.Configuration.ConfigurationManager.AppSettings["CacheTime"];

        //        int timeSpan = 0;

        //        bool b = int.TryParse(timeSpanStr, out timeSpan);
        //        if (!b)
        //        {
        //            // 默认60分钟过期
        //            timeSpan = 60;
        //        }


        //        fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
        //        text = Utility.ReadText(fileName, System.Text.Encoding.GetEncoding("GB2312"));

        //        SetFileCache(key, text, fileName, timeSpan);
        //    }

        //    return text;
        //}

        public static void SetFileCache(string key, object objObject, string file, int cacheTime)
        {
            CacheDependency mydepen = new CacheDependency(file);
            System.Web.Caching.Cache objCache = HttpRuntime.Cache;

            objCache.Insert(key, objObject, mydepen, DateTime.Now.AddMinutes(cacheTime), TimeSpan.Zero, CacheItemPriority.Normal, null);
        }
    }
}
